/*
题目链接:https://leetcode.cn/problems/difference-of-number-of-distinct-values-on-diagonals/description/?envType=daily-question&envId=2025-03-25
*/
//题解代码:

class Solution {
public:
    vector<vector<int>> differenceOfDistinctValues(vector<vector<int>>& grid) {
        int n = grid.size(),m = grid[0].size();
        vector<vector<int>> leftup(n,vector<int>(m));
        vector<vector<int>> rightdown(leftup);
        auto f = [&](int i,int j,int move[],vector<vector<int>>& cnt)->void{
            unordered_set<int> ust;
            while(i>=0 && i<n && j>=0 && j<m){
                ust.insert(grid[i][j]);
                cnt[i][j] = ust.size();
                i += move[0], j += move[1];
            }
        };
        int mv1[2] = {1,1},mv2[2] ={-1,-1};
        for(int j=0;j<m;++j) f(0,j,mv1,leftup),f(n-1,j,mv2,rightdown);
        for(int i=0;i<n;++i) f(i,0,mv1,leftup),f(i,m-1,mv2,rightdown);
        vector<vector<int>> ans(n,vector<int>(m));
        for(int i=0;i<n;++i){
            for(int j=0;j<m;++j){
                ans[i][j] = abs((i>0&&j>0 ? leftup[i-1][j-1] : 0) - (i<n-1&&j<m-1 ? rightdown[i+1][j+1] : 0));
            }
        }
        return ans;
    }
};
